package com.ht.web_vr_home_tour_backend.config.web;

import cn.hutool.core.io.IORuntimeException;
import com.ht.web_vr_home_tour_backend.obj.dto.ResData;
import com.ht.web_vr_home_tour_backend.utils.exceptions.ControllerParamException;
import com.ht.web_vr_home_tour_backend.utils.exceptions.MessageException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MultipartException;

import javax.servlet.http.HttpServletResponse;
import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionAdvice {
    @ExceptionHandler(MessageException.class)
    public ResData<Void> handleMessageException(MessageException e, HttpServletResponse response) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return ResData.fail(e.getMessage());
    }

    @ExceptionHandler(IORuntimeException.class)
    public ResData<Void> handleIoRuntimeException(IORuntimeException e, HttpServletResponse response) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return ResData.fail("服务器IO错误，请稍后重试");
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ResData<Void> handleHttpMessageNotReadableException (HttpMessageNotReadableException e, HttpServletResponse response) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        log.warn("传入参数错误", e);
        return ResData.fail("传入参数错误，请检查输入参数");
    }

    @ExceptionHandler(MultipartException.class)
    public ResData<Void> handleMultipartException(MultipartException e, HttpServletResponse response) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        if (e.getMessage().startsWith("Maximum upload size exceeded")) {
            return ResData.fail("上传文件过大，请更换文件重试");
        }
        log.warn("MultipartFile 错误", e);
        return ResData.fail("上传方式错误，请重试");
    }

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public ResData<Void> handleSQLIntegrityConstraintViolationException(SQLIntegrityConstraintViolationException e, HttpServletResponse response) {
        response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        log.error("数据库错误", e);
        return ResData.fail("系统错误，请稍后重试");
    }

    @ExceptionHandler(ControllerParamException.class)
    public ResData<Void> handleControllerParamException(ControllerParamException e, HttpServletResponse response) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        log.warn("参数错误", e);
        return ResData.fail(e.getMessage());
    }

    @ExceptionHandler(NullPointerException.class)
    public ResData<Void> handleNullPointerException(NullPointerException e, HttpServletResponse response) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        log.warn("参数错误", e);
        return ResData.fail("参数错误");
    }

    @ExceptionHandler(Exception.class)
    public ResData<Void> handleException(Exception e, HttpServletResponse response) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        log.error(e.getMessage(), e);
        return ResData.fail("系统错误，请稍后重试");
    }

    /**
     * JSR303 校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResData<Void> handle(MethodArgumentNotValidException e){
        StringBuilder message = new StringBuilder();
        e.getBindingResult().getAllErrors().forEach(err -> {
            message.append(err.getDefaultMessage()).append(".");
        });
        return ResData.fail(message.toString());
    }

    /**
     * 数据校验异常
     */
    @ExceptionHandler({DataIntegrityViolationException.class,
            IllegalArgumentException.class})
    public ResData<Void> handleDataIntegrityViolationException(Exception e) {
        if (e.getMessage().startsWith("Duplicate entry")) {
            return ResData.fail("数据重复，请检查后重试");
        }
        log.warn(e.getMessage(), e);
        return ResData.fail("数据校验异常，请检查后重试");
    }
}
